package org.amos.core.frame.filter;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.amos.core.basic.utils.HttpUtils;
import org.amos.core.basic.vo.R;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @desc: 演示环境 过滤器
 * @author: liubt
 * @date: 2023-11-15 13:17
 **/
@Order(1)
@Component
public class DemoFilter extends OncePerRequestFilter implements InitializingBean {

    /**
     * AntPath规则匹配器
     */
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
    /**
     * 演示环境开关
     */
    @Value("${amos.demo.is-enabled:false}")
    private Boolean demoEnabled;

    /**
     * 排除的路径
     */
    @Value("${amos.demo.exclude-urls:[]}")
    protected List<String> excludeUrls;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws IOException {
        HttpUtils.write(response, R.error("演示环境，不支持该操作"));
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        // 关闭直接跳过
        if (!demoEnabled) {
            return true;
        }

        // 请求类型检查
        if (!StrUtil.equalsAnyIgnoreCase(request.getMethod(), "POST", "PUT", "DELETE", "PATCH")) {
            return true;
        }

        // 请求路径检查
        String requestUri = request.getRequestURI();
        // 此路径是否不需要处理
        for (String exclude : excludeUrls) {
            if (ANT_PATH_MATCHER.match(exclude, requestUri)) {
                return true;
            }
        }

        return false;
    }

    @Override
    public void afterPropertiesSet() {
        if (excludeUrls == null) {
            excludeUrls = new ArrayList<>();
        }
        excludeUrls.add("/auth/**");
    }
}
